<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
        <!--角色数据-->
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px" v-show="showSearch" >

          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="角色状态" prop="statusCode">
            <el-select @change="handleQuery" v-model="queryParams.statusCode" size="small" clearable style="width: 150px" placeholder="请选择">
              <el-option key="" label="全部" value=""/>
              <el-option v-for="item in statusOptions" :key="item.dictCode" :label="item.dictName" :value="item.dictCode"/>
            </el-select>
          </el-form-item>

          <el-form-item label="备注说明" prop="remark">
            <el-input v-model="queryParams.remark" placeholder="请输入备注说明" size="small" clearable style="width: 150px"/>
          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker @change="handleQuery" v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
          </el-form-item>

          <el-form-item>
            <el-button type="primary"  size="mini" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary"  v-hasPermi="['saveSystemRole']"  icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" v-hasPermi="['updateSystemRole']"  icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" v-hasPermi="['deleteSystemRole']"  icon="el-icon-delete" size="mini" :disabled="single" @click="handleDelete">删除</el-button>
          </el-col>

          <right-toolbar :showSearch.sync="showSearch" @queryTable="querySystemRolePageResList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table ref="multipleTable" :stripe="true" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange"
                  @sort-change='tableSortChange' :default-sort="{prop: 'sort', order: 'descending'}">
          <el-table-column type="selection" align="center"/>
          <el-table-column label="角色名称" align="left" prop="roleName" width="300" />
          <el-table-column label="角色状态" align="left" prop="statusName" width="150" >
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.statusColor">{{scope.row.statusName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="数据范围" align="left" prop="dataScopeName" width="250" >
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.dataScopeColor">{{scope.row.dataScopeName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注说明" align="left" prop="remark"/>
          <el-table-column label="所属部门" align="left" prop="createDeptName" width="200"/>
          <el-table-column label="创建时间" align="left" prop="createTime" sortable='custom' width="200" />
          <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" v-hasPermi="['updateSystemRole']" icon="el-icon-edit"  @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="mini" type="text" v-hasPermi="['deleteSystemRole']" icon="el-icon-delete"  @click="handleDelete(scope.row)">删除</el-button>
              <el-button size="mini" type="text" v-hasPermi="['saveRoleBindingMenu']" icon="el-icon-circle-check"  @click="saveRoleBindingMenu(scope.row)">授权</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows"
                    @pagination="querySystemRolePageResList"/>
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="addUpdateOpen" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="addUpdateOpenRules"  label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.roleName" placeholder="请输入角色名称" minlength="1"/>
        </el-form-item>

        <el-form-item label="角色状态" prop="statusCode">
          <el-select :hide-required-asterisk="true" v-model="form.statusCode" clearable placeholder="请选择"  style="width: 100%;">
            <el-option
              v-for="item in statusOptions"
              :key="item.dictCode"
              :label="item.dictName"
              :value="item.dictCode"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注说明" prop="remark">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.remark" placeholder="请输入备注说明" minlength="1"/>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number :hide-required-asterisk="true" v-model="form.sort" :min="1" :max="9999" label="排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelAddUpdateOpen">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色数据权限对话框 -->
    <el-dialog :title="title" :visible.sync="roleAuthorizationOpen" width="800px" append-to-body>
      <el-row :gutter="24">
        <el-form  ref="formAuthorization"  :model="form" label-width="80px">
          <el-col :span="24">
            <el-form-item label="角色名称">
              <el-input v-model="form.roleName" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="数据范围">
              <el-select v-model="form.dataScopeCode" @change="dataScopeSelectChange" style="width: 100%">
                <el-option v-for="item in dataScopeOptions" :key="item.dictCode" :label="item.dictName" :value="item.dictCode"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="菜单权限">
              <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开</el-checkbox>
              <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选</el-checkbox>
              <el-tree
                class="flow-tree"
                :data="menuOptions"
                check-on-click-node
                show-checkbox
                default-expand-all
                ref="menu"
                node-key="id"
                empty-text="加载中，请稍候"
                :props="menuDefaultProps"
              ></el-tree>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-show="form.dataScopeCode === 'CUSTOM_DATA'">
            <el-form-item label="数据权限">
              <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')">展开</el-checkbox>
              <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')">全选</el-checkbox>
              <el-checkbox v-model="form.deptCheckStrictly" @change="handleCheckedTreeConnect($event, 'dept')">父子联动</el-checkbox>
              <el-tree
                class="flow-tree"
                :data="deptOptions"
                check-on-click-node
                show-checkbox
                default-expand-all
                ref="dept"
                node-key="id"
                :check-strictly="!form.deptCheckStrictly"
                empty-text="加载中，请稍候"
                :props="deptDefaultProps"
              ></el-tree>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSaveRoleBindingMenu">确 定</el-button>
        <el-button @click="cancelAddUpdateOpen">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { queryBindingRoleUseMenuTreeResList } from '@/api/system/systemMenu'
  import { queryNormalSelectSystemDeptTreeResList } from '@/api/system/systemDept'
  import { querySystemRolePageResList,
    deleteSystemRoleByRoleId,
    saveSystemRole,
    saveRoleAuthorization,
    updateSystemRole,
    querySystemRoleResByRoleId,
    querySystemMenuIdListByRoleId,
    querySystemDeptIdListByRoleId} from '@/api/system/systemRole'
  import { getDicListByDictCodeList } from '@/api/common/dict'
  //默认查询参数
  let defaultQueryParams = {
    roleName: undefined,
    remark: undefined,
    startTime: undefined,
    endTime: undefined,
    statusCode:"",
    createUserName: undefined,
    createDeptId: undefined,
    page: 1,
    rows: 10
  }
  export default {
    name: "systemRoleAdmin",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 显示搜索条件
        showSearch: true,
        // table表格数据
        dataList: [],
        // 日期范围
        dateRange: [],
        // 弹出层标题
        title: "",
        // 是否显示新增修改弹出层
        addUpdateOpen: false,
        //是否显示授权弹出层
        roleAuthorizationOpen:false,
        // 用户状态
        statusOptions: [],
        //角色数据范围
        dataScopeOptions:[],
        // 菜单列表
        menuOptions: [],
        //展开/折叠
        menuExpand: true,
        //全选/全不选
        menuNodeAll: false,
        //defaultProps(默认参数)
        menuDefaultProps: {
          children: "children",
          label: "menuName"
        },
        // 部门列表
        deptOptions: [],
        //展开/折叠
        deptExpand: true,
        //全选/全不选
        deptNodeAll:false,
        //defaultProps(默认参数)
        deptDefaultProps: {
          children: "children",
          label: "deptName"
        },
        // 增加修改表单参数
        form: {},
        // 查询参数
        queryParams: { ...defaultQueryParams },
        //列信息
        columns: [],
        // 新增修改表单校验
        addUpdateOpenRules: {
          roleName: [
            { required: true, message: "角色名称不能为空",trigger: "blur" },
          ],
          statusCode: [
            { required: true, message: "角色状态必须选择",trigger: "blur" }
          ],
          sort: [
            { required: true, message: "排序不能为空",trigger: "blur" }
          ]
        }
      }
    },
    created() {
      this.querySystemRolePageResList();
      this.initDict();
    },

    methods: {
      //获取数据字典
      initDict(){
        let dictArr = ["STATUS","DATA_SCOPE"];
        getDicListByDictCodeList(dictArr).then(res => {
          this.statusOptions = JSON.parse(JSON.stringify(res.data['STATUS']));
          this.dataScopeOptions = JSON.parse(JSON.stringify(res.data['DATA_SCOPE']));
        });
      },
      /** 查询角色列表 */
      querySystemRolePageResList() {
        this.loading = true
        querySystemRolePageResList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.dataList = response.data.records
          this.total = response.data.total
          this.loading = false
        })
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.roleId)
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },
      //排序
      tableSortChange(column){
        //格式化排序参数，构建中
        this.orderByFormat(this.queryParams,column);
        //执行查询方法
        this.querySystemRolePageResList()
      },
      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "saveRoleBindingMenu":
            this.saveRoleBindingMenu(row);
            break;
          default:
            break;
        }
      },

      /** 分配数据权限操作 */
      saveRoleBindingMenu(row) {
        this.reset();
        const roleId={roleId:row.roleId};
        this.queryNormalSelectSystemDeptTreeResList();
        this.queryBindingRoleUseMenuTreeResList();
        querySystemRoleResByRoleId(roleId).then(response => {
          this.form = response.data;
          this.roleAuthorizationOpen = true;
          this.$nextTick(() => {
            this.setMenuCheckedKeys(row.roleId);
            if (this.form.dataScopeCode === 'CUSTOM_DATA') {
              this.setDeptCheckedKeys(row.roleId);
            }
          });
          this.title = "角色授权";
        });
      },
      /** 查询菜单树结构 */
      queryBindingRoleUseMenuTreeResList() {
        queryBindingRoleUseMenuTreeResList().then(response => {
          this.menuOptions = response.data;
        });
      },
      /** 查询部门树结构 */
      queryNormalSelectSystemDeptTreeResList() {
        queryNormalSelectSystemDeptTreeResList({}).then(response => {
          this.deptOptions = response.data;
        });
      },

      /** 选择角色权限范围触发 */
      dataScopeSelectChange(value) {
        if(value !== 'CUSTOM_DATA') {
          this.$refs.dept.setCheckedKeys([]);
        }else{
          this.setDeptCheckedKeys(this.form.roleId);
        }
      },

      //设置菜单tree默认选中
      setMenuCheckedKeys(roleId){
        querySystemMenuIdListByRoleId({"roleId":roleId}).then(response => {
          let menuIdArr=[];
          const dataRes = response.data;
          for (let j = 0; j < dataRes.length; j++) {
            const menuId = dataRes[j];
            let key=this.getNodeKeys(menuId,this.menuOptions);
            if(key!==''){
              menuIdArr.push(key);
            }
          }
          //设置选中节点
          this.$refs.menu.setCheckedKeys(menuIdArr);
          //设置全选中
          this.menuNodeAll = this.menuOptions.length===dataRes.length;
        });
      },

      //获取选中的子节点
      getNodeKeys(keyId,childrens){
        let key="";
        for (let i = 0; i < childrens.length; i++) {
          const item = childrens[i];
          let id=item.id;
          let childs=item.children;
          if(id===keyId){//如果相等
            if(childs&&childs.length>0){
              key=this.getNodeKeys(keyId,childs)
            }else{  //没有子节点
              return keyId;
            }
          }else if(childs&&childs.length>0){
            key=this.getNodeKeys(keyId,childs);
          }
          if(key!==''){
            return key;
          }
        }
        return key;
      },

      //设置部门tree默认选中
      setDeptCheckedKeys(roleId){
        querySystemDeptIdListByRoleId({"roleId":roleId}).then(response => {
          let deptIdArr=[];
          const dataRes = response.data;
          for (let j = 0; j < dataRes.length; j++) {
            const deptId = dataRes[j];
            let key=this.getNodeKeys(deptId,this.deptOptions);
            if(key!==''){
              deptIdArr.push(key);
            }
          }
          //设置选中节点
          this.$refs.dept.setCheckedKeys(deptIdArr);
          //设置全选中
          this.deptNodeAll = this.deptOptions.length===dataRes.length;
        });
      },

      // 树权限（展开/折叠）
      handleCheckedTreeExpand(value, type) {
        if (type === 'menu') {
          let treeList = this.menuOptions;
          for (let i = 0; i < treeList.length; i++) {
            this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
          }
        } else if (type === 'dept') {
          let treeList = this.deptOptions;
          for (let i = 0; i < treeList.length; i++) {
            this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
          }
        }
      },
      // 树权限（全选/全不选）
      handleCheckedTreeNodeAll(value, type) {
        if (type === 'menu') {
          this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
        } else if (type === 'dept') {
          this.$refs.dept.setCheckedNodes(value ? this.deptOptions: []);
        }
      },
      // 树权限（父子联动）
      handleCheckedTreeConnect(value, type) {
        if (type === 'menu') {
          this.form.menuCheckStrictly = value;
        } else if (type === 'dept') {
          this.form.deptCheckStrictly = value;
        }
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.addUpdateOpen = true;
        this.title = "添加角色";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        //修改表单填充
        this.form = {...row};
        this.addUpdateOpen = true;
        this.title = "修改角色";
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        this.$confirm('确认删除"' + row.roleName + '"角色吗？', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          const roleId={roleId:row.roleId}
          return deleteSystemRoleByRoleId(roleId);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.querySystemRolePageResList();
        }).catch(function() {});
      },

      /** 提交保存或修改按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.roleId !== undefined) {
              updateSystemRole(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.querySystemRolePageResList();
                this.addUpdateOpen = false
              });
            } else {
              saveSystemRole(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.querySystemRolePageResList();
                this.addUpdateOpen = false
              });
            }
          }
        });
      },

      // 所有菜单节点数据
      getMenuAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getCheckedKeys();
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      },
      // 所有部门节点数据
      getDeptAllCheckedKeys() {
        // 目前被选中的部门节点
        let checkedKeys = this.$refs.dept.getCheckedKeys();
        // 半选中的部门节点
        let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      },
      /** 提交按钮（数据权限） */
      submitSaveRoleBindingMenu: function() {
        if (this.form.roleId !== undefined) {
          const form = {
            roleId: this.form.roleId,
            menuIdList: this.getMenuAllCheckedKeys(),
            deptIdList: this.getDeptAllCheckedKeys(),
            dataScopeCode: this.form.dataScopeCode
          }
          if (this.form.dataScopeCode !== 'CUSTOM_DATA') {
            form.deptIdList = [];
          }
          saveRoleAuthorization(form).then(response => {
            this.$modal.msgSuccess(response.message)
            this.querySystemRolePageResList();
            this.roleAuthorizationOpen = false;
          });
        }
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1
        this.querySystemRolePageResList()
      },
      /** 重置按钮操作 */
      resetQuery(fromId) {
        this.dateRange = [];
        this.resetForm(fromId);
        this.handleQuery()
      },
      // 取消修改增加弹出层按钮
      cancelAddUpdateOpen() {
        this.addUpdateOpen = false
        this.roleAuthorizationOpen = false
      },
      // 表单重置
      reset() {
        if (this.$refs.menu !== undefined) {
          this.$refs.menu.setCheckedKeys([]);
        }
        if (this.$refs.dept !== undefined) {
          this.$refs.dept.setCheckedKeys([]);
        }
        this.form = {
          roleId: undefined,
          roleName: undefined,
          dataScopeCode: undefined,
          remark: undefined,
          deptCheckStrictly: true,
          sort: 1,
          statusCode: "NORMAL"
        };
        this.resetForm('form')
      }
    }
  }
</script>
<style rel="stylesheet/scss" lang="scss">
  .flow-tree{
    overflow-y:auto;
    border:1px solid #E7E7E7;
    height:300px;
  }
</style>
